<template>
  <!-- <iframe-view :url="url" /> -->
  <div class="app-container" v-loading="loading">
    <el-form :model="queryParams" v-show="showSearch" ref="queryForm" :inline="true">
      <el-form-item label="流程实例ID" prop="processInstanceId">
        <el-input
          v-model="queryParams.processInstanceId" placeholder="流程实例ID精确查询" clearable size="default" style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="流程编码" prop="wfCodeLike">
        <el-input
          v-model="queryParams.wfCodeLike" placeholder="流程编码模糊查询" clearable size="default" style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="业务KEY" prop="businessKeyLike">
        <el-input
          v-model="queryParams.businessKeyLike" placeholder="业务Key模糊查询" clearable size="default" style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="流程主题" prop="businessSubjectLike">
        <el-input v-model="queryParams.businessSubjectLike" placeholder="主题模块查询" clearable size="default" style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="发起时间">
        <el-date-picker
          v-model="dateRange" size="default" style="width: 240px" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" :perm="['wf:manager:instance:search']" />
        <reset-button @click="resetQuery" :perm="['wf:manager:instance:search']" />
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>
    <el-table :data="instanceList">
      <el-table-column label="流程实例ID" prop="processInstanceId" width="200" />
      <el-table-column label="业务KEY" prop="businessKey" width="150" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="流程主题" prop="businessSubject" min-width="250" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="流程发起人" prop="userName" width="220" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ scope.row.starter && (scope.row.starter.userName+"("+scope.row.starter.loginName+")") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程名称" prop="deploymentName" min-width="200" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ scope.row.deploymentName+"("+scope.row.processDefinitionId+")" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发起时间" align="center" prop="processCreateTime" width="160" />
      <el-table-column label="结束时间" align="center" prop="processEndTime" width="160" />
      <el-table-column label="状态" align="center" prop="processEndTime" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.processEndTime == null ? 'success' : 'info'" disable-transitions>{{
            scope.row.processEndTime == null ? "运行中" : "已结束"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" fixed="right">
        <template #default="scope">
          <div class="operation">
            <text-button text="流程变量" icon="Document" :perm="['wf:manager:instance:search']" @click="viewVariables(scope.$index, scope.row)" />
            <text-button text="审批过程" icon="Document" :perm="['wf:manager:instance:search']" @click="viewApproveHistory(scope.row)" />
            <el-dropdown v-if="scope.row.processEndTime == null">
              <span class="ml10 operation-drop">
                <text-button text="更多" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <text-delete-button text="终止" @click="remove(scope.row)" :perm="['wf:manager:instance:remove']" :subject="scope.row.businessSubject" />
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <text-button text="减签" icon="Document" :perm="['wf:manager:instance:update']" @click="viewReduceTaskPage(scope.row)" :subject="scope.row.businessSubject" />
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <text-button text="升级" icon="upload" :perm="['wf:manager:instance:update']" @click="upgradeProcess(scope.row)" :subject="scope.row.businessSubject" />
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 流程变量 -->
    <drag-dialog title="查看流程变量" v-model="dialogVisible" width="80%" style="max-height: 800px">
      <pre style="white-space: pre-wrap">{{
        instanceList[index] &&
        instanceList[index].params &&
        JSON.stringify(
          instanceList[index].params,
          // JSON.parse(instanceList[index].params.variables),
          null,
          4
        )
      }}</pre>
    </drag-dialog>

    <!-- 查询审批记录 -->
    <drag-dialog :title="title" :close-on-click-modal="false" v-model="showHistoryOpen" width="80%" append-to-body @close="cancel">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="审批记录" name="first">
          <wf-approve-history v-if="activeName === 'first'" :processInstanceId="processInstanceId" :wfStatusOptions="wfStatusOptions" />
        </el-tab-pane>
        <el-tab-pane label="审批流程" name="second">
          <bpmn-viewer v-if="isFlowable && showHistoryOpen && activeName === 'second'" :wfCode="wfCode" :deploymentId="deploymentId" :processInstanceId="processInstanceId" />
          <wf-run-image v-else :processInstanceId="processInstanceId" :showCurrentApproverList="showCurrentApproverList" />
        </el-tab-pane>
        <el-tab-pane label="当前审批人" name="third">
          <WfApproveList v-if="activeName === 'third'" :processInstanceId="processInstanceId" :showCurrentApproverList="showCurrentApproverList" />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showHistoryOpen=false">关 闭</el-button>
        </div>
      </template>
    </drag-dialog>

    <!-- 查询减签界面 -->
    <drag-dialog :title="title" :close-on-click-modal="false" v-model="showReduceTaskPageOpen" width="80%" append-to-body @close="cancel">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="可减签任务" name="first">
          <WfReduceApproveList v-if="activeName === 'first'" :processInstanceId="processInstanceId" :showCurrentApproverList="showCurrentApproverList" />
        </el-tab-pane>
        <el-tab-pane label="审批流程" name="second">
          <bpmn-viewer v-if="isFlowable && showReduceTaskPageOpen && activeName === 'second'" :wfCode="wfCode" :processInstanceId="processInstanceId" />
          <wf-run-image v-else :processInstanceId="processInstanceId" :showCurrentApproverList="showCurrentApproverList" />
        </el-tab-pane>
        <el-tab-pane label="审批记录" name="third">
          <wf-approve-history v-if="activeName === 'third'" :processInstanceId="processInstanceId" :wfStatusOptions="wfStatusOptions" />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showReduceTaskPageOpen = false">关 闭</el-button>
        </div>
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import {
  listInstance,
  delInstance,
} from "@wf/api/wf/instance";
import { debounceWrapper } from "@/utils/zmids";
import WfRunImage from '@/components/Zmids/Workflow/WfRunImage.vue';
import WfApproveHistory from '@/components/Zmids/Workflow/WfApproveHistory.vue';
import TextButton from '@/components/Zmids/Buttons/TextButton.vue';
import WfApproveList from '@/components/Zmids/Workflow/WfApproveList.vue';
import WfReduceApproveList from '@/components/Zmids/Workflow/WfReduceApproveList.vue';
import BpmnViewer from '@wf/components/bpmnjs/bpmnViewer'
import {isEnableUpgrade,upgradeWfInstanceByProcessInstanceId} from "@/platform/wf/api/wf/instance.js";

export default {
  name: "WfManagerInstance",
  components: { WfReduceApproveList, TextButton, WfRunImage, WfApproveHistory, WfApproveList, BpmnViewer },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 默认激活的tab页
      activeName: 'first',
      // 选择的流程实例ID
      processInstanceId: "",
      deploymentId: "",
      // 是否显示当前审批人列表
      showCurrentApproverList: false,
      // 显示搜索条件
      showSearch: true,
      // 日期范围
      dateRange: [],
      //流程状态
      wfStatusOptions: [],
      title: "",
      dialogVisible: false,
      showHistoryOpen: false,
      showReduceTaskPageOpen: false,
      showFlowOpen: false,
      showHistoryList: [],
      currentPage: 1,
      pagesize: 10,
      // 总条数
      total: 0,
      instanceList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processInstanceId: undefined,
        businessKeyLike: undefined,
        businessSubjectLike: undefined,
      },
      index: 0,
      wfCode: ''
    };
  },
  computed: {
    isFlowable(){
      return import.meta.env.VITE_FLOW_TYPE == 'flowable'
    }
  },
  created() {
    this.getList();
    this.getDicts("wf_approve_status").then((response) => {
      this.wfStatusOptions = response.data;
    });
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //部署管理列表查询
    getList: debounceWrapper(function () {
      this.loading = true;
      listInstance(
        this.addDateRange(
          this.queryParams,
          ["processCreateTimeStart", "processCreateTimeEnd"],
          this.dateRange
        )
      ).then((response) => {
        this.instanceList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    }),
    //流程变量
    viewVariables: debounceWrapper(function (index, row) {
      this.loading = true;
      listInstance(
        this.addDateRange(
          this.queryParams,
          ["processCreateTimeStart", "processCreateTimeEnd"],
          this.dateRange
        )
      ).then((response) => {
        this.loading = false;
        this.instanceList = response.data.list;
        this.total = response.data.total;
        this.dialogVisible = true;
        this.index = index;
      });
    }),
    // 查询审批过程
    viewApproveHistory: debounceWrapper(function (row) {
      this.title = "审批过程";
      this.processInstanceId = row.processInstanceId;
      this.deploymentId = row.deploymentId
      this.showCurrentApproverList = (row.processEndTime == null);
      this.showHistoryOpen = true;
    }),
    // 查看减签页面
    viewReduceTaskPage: debounceWrapper(function (row) {
      this.title = '减签';
      this.processInstanceId = row.processInstanceId;
      this.wfCode = row.wfCode;
      this.showCurrentApproverList = row.processEndTime == null;
      this.showReduceTaskPageOpen = true;
    }),
    // 升级流程版本
        upgradeProcess(row){
          // 检查是否可升级，如果可以升级，弹窗确定是否要升级
          isEnableUpgrade(row.processInstanceId).then((response) => {
            if (response.data === 'true') {
              this.$confirm('是否确认升级流程版本？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // 升级流程版本
                upgradeWfInstanceByProcessInstanceId(row.processInstanceId).then((response) => {
                  this.msgSuccess("升级流程版本成功");
                  this.getList();
                });
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消升级'
                });
              });
            } else if (response.data === 'false') {
              this.$message({
                type: 'info',
                message: '该流程实例未通过校验，暂不支持升级'
              });
            } else if (response.data === 'latest'){
              this.msgSuccess("当前流程版本已经是最新版本");
            }
          })
        },
    // 统一取消按钮
    cancel() {
      this.showHistoryOpen = false;
      this.showFlowOpen = false;
      this.reset();
    },
    // 流程状态字典翻译
    wfStatusFormat(row, column) {
      return this.selectDictLabel(this.wfStatusOptions, row.isApprove);
    },
    //重置
    reset() {
      this.title = "";
    },
    // 终止
    remove: debounceWrapper(function (row) {
      this.loading = true;
      delInstance(row.processInstanceId).then((response) => {
        this.loading = false;
        if (response.data === true) {
          this.msgSuccess("终止成功");
          this.getList();
        }
      });
    }),
  },
};
</script>
<style lang="scss" scoped>
.operation {
  display: flex;
  align-items: center;

  &-drop {
    display: flex;
    align-items: center;
  }
}
</style>